// pages/my/bindingDevice/bindingRing/bindingRing.js
var app = getApp();
var plugin = requirePlugin("myPlugin");

Page({
  data: {

  },
  onShow: function () {
    var that = this;
    app.middleware.requestAjax({
      serAddr: app.serAddrs.getUserEquipment,
      data: {
        type: 1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      cancelToast: true,
      success: function (res) {
        console.log('获取用户绑定的所有手环', res);
        try {
          var jsonHandles = [];
          for (var i = 0; i < res.data.userEquipmentList.length; i++) {
            res.data.userEquipmentList[i].equipmentId = parseInt(res.data.userEquipmentList[i].equipmentId, 16);
            jsonHandles.push(res.data.userEquipmentList[i].equipmentId);
          }
          plugin.setHand(JSON.stringify(jsonHandles));

          that.setData({
            userEquipmentList: res.data.userEquipmentList
          })
        } catch (e) {

        }
      }
    })
  },
  add_device: function () {
    var that = this;
    wx.scanCode({
      success: function (res) {
        console.log('扫码的结果', res);
        var options = that.MtQRcodeParse(res.result);
        console.log('字段处理', options);
        if (options && options.moduleType >= 121 && options.moduleType <= 154) {
          //只要设备类型 在 121~154 中间，那就是手环了
          console.log('是手环的二维码');

          app.middleware.requestAjax({
            serAddr: app.serAddrs.addUserEquipment,
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              equipmentId: options.deviceId
            },
            success: function (res) {
              console.log('添加设备', res);
              if (res.status == 200) {
                wx.showToast({
                  title: '手环设备绑定成功',
                  icon: "none",
                })
              } else {
                wx.showToast({
                  title: '手环设备绑定失败',
                  icon: "none",
                })
              }
              that.onShow();
            }
          })
        } else {
          wx.showToast({
            title: '该二维码不是手环二维码',
          })
        }

      }
    })




  },

  // 二维码字段处理
  MtQRcodeParse: function (value) {
    var that = this;
    var link = value.split('=');
    var arr = [];
    if (!link[0]) return false;

    if (link.length > 1) {
      arr = link[1];
    } else {
      arr = link[0];
    }
    arr = arr.split('M');
    if (arr.length < 4) return false;
    var newArray = {
      'company_hardware': arr[0],
      'address': that.str_pad(arr[1]),
      'deviceId': arr[2],
      'moduleType': parseInt(arr[3], 16),
    }
    // 定制版唯一
    if (arr[4]) {
      newArray.onlyNo = arr[4];
    }
    return newArray;
  },
  str_pad: function (hex) {
    var zero = '00000000';
    var tmp = 8 - hex.length;
    return zero.substr(0, tmp) + hex;
  },
})